package com.ruicar.afs.cloud.afscase.job.approve;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.ApproveTeleRecord;
import com.ruicar.afs.cloud.afscase.approvetask.service.ApproveTeleRecordService;
import com.ruicar.afs.cloud.common.job.core.biz.model.ReturnT;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJob;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJobHandler;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: 定时任务
 * @author jiaqi.guo
 * @created 2020/10/11 16:53
 * @version 1.0
 */
@AfsJob
@AllArgsConstructor
@Slf4j
@Component
public class ApproveCommonJob {

    private ApproveTeleRecordService teleRecordService;
    /**
     * 批量获取语音转文本
     */
    @AfsJobHandler(value = "obtainMessageInfo")
    public ReturnT<String> obtainMessageInfo(String param){
        log.info("启动定时任务【批量获取语音转文本】");
        List<ApproveTeleRecord> teleRecordList=teleRecordService.list(Wrappers.<ApproveTeleRecord>query().lambda()
        .ne(ApproveTeleRecord::getIsConversion,WhetherEnum.NO.getCode()));
        teleRecordList.forEach(teleRecord->{
            JSONObject jsonObject=teleRecordService.getMessageInfo(teleRecord.getTelTaskId());
            if(ObjectUtils.isNotEmpty(jsonObject)){
                log.info("语音转文本返回："+jsonObject.toString());
                JSONObject json=jsonObject.getJSONObject("payload");
                if(ObjectUtils.isNotEmpty(json)){
                    JSONArray array=json.getJSONArray("sentences");
                    if(CollectionUtils.isNotEmpty(array)
                            &&ObjectUtils.isNotEmpty(array.getJSONObject(0))){
                        /**获取语音文本*/
                        String text=array.getJSONObject(0).getString("text");
                        log.info("输出文本:{}",text);
                        teleRecord.setRecordText(text);
                        teleRecord.setIsConversion(WhetherEnum.YES.getCode());
                        teleRecordService.updateById(teleRecord);
                    }else{
                        log.info("响应无文本数据读取:{}",json.toString());
                    }
                }
            }else{
                log.info("获取语音文本响应失败:{}",teleRecord.getApplyNo());
            }
        });
        log.info("定时任务【批量获取语音转文本】执行成功");
        return ReturnT.SUCCESS;
    }
}
